package wubj.com.uploaddemo.upload;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


abstract class BaseDb {

    protected DBHelper helper = null;

    protected SQLiteDatabase db = null;

    public BaseDb() {

    }

    public BaseDb(Context context) {
        helper = DBHelper.getInstance(context);
        db = helper.getWritableDatabase();
    }

    public void beginTransaction() {
        if (db == null || !db.isOpen()) {
            db = helper.getWritableDatabase();
        }
        db.beginTransaction();
    }

    public void endTransaction() {
        if (db == null || !db.isOpen()) {
            db = helper.getWritableDatabase();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    protected void checkDb() {
        if (db == null || !db.isOpen()) {
            db = helper.getWritableDatabase();
        }
    }

    public void closeDbAndCursor(Cursor cursor) {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
        /*
         * if (db != null) { db.close(); db = null; }
		 */
    }

    protected void clearAllData() {
        try {
            checkDb();
            String sql = "delete from " + getTableName() + ";";
            db.execSQL(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    protected boolean isHasData() {
        checkDb();
        String sql = "select * from " + getTableName();
        Cursor cursor = null;
        try {
            cursor = db.rawQuery(sql, null);
            return (cursor != null && cursor.getCount() > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeDbAndCursor(cursor);
        }
        return false;
    }

    abstract String getTableName();

    protected static byte[] getBytesFromObject(Object record) {
        try {
            ByteArrayOutputStream bar = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bar);
            oos.writeObject(record);
            byte[] data = bar.toByteArray();
            oos.close();
            bar.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // return Object
    protected static Object getObjectFromBytes(byte[] data) {
        try {
            ByteArrayInputStream bar = new ByteArrayInputStream(data);
            ObjectInputStream ois = new ObjectInputStream(bar);
            Object obj = ois.readObject();
            ois.close();
            bar.close();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
